﻿using GuanYijia.Application.OutPut;
using GuanYijia.DoMain;
using GuanYijia.Repository;
using GuanYiJia.WebApi;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Panda.DynamicWebApi;
using Panda.DynamicWebApi.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GuanYijia.Application.MatericalCategoryManagement
{
    [DynamicWebApi]
    [ApiExplorerSettings(GroupName = "v1")]
    [Authorize]
    public class MatericalCategoryDataService : IDynamicWebApi, IMatericalCategoryDataService
    {
        private readonly IBaseRepository<MaterialCategory> _materialCategoryRepository;
        private readonly IBaseRepository<ProductInfo> _productInfoRepository;

        public MatericalCategoryDataService(IBaseRepository<MaterialCategory> materialCategoryRepository, IBaseRepository<ProductInfo> productInfoRepository)
        {
            _materialCategoryRepository = materialCategoryRepository;
            _productInfoRepository = productInfoRepository;
        }
        [SkipCustomFilterAttribute]
        /// <summary>
        /// 商品类型级联
        /// </summary>
        /// <returns></returns>
        public async Task<List<Cascader>> GetMaterialCategoryTree()
        {
            List<Cascader> list = new List<Cascader>();
            var result = await _materialCategoryRepository.GetAllAsync();
            var firstCategory = result.Where(p => p.parent_id == 0).OrderBy(p => p.sort);
            foreach (var item in firstCategory)
            {
                Cascader cascader = new Cascader();
                cascader.Value = item.category_id;
                cascader.Label = item.name;
                cascader.Children = new List<Cascader>();
                list.Add(cascader);
                GetNextCategory(result, cascader);
            }
            return list;
        }
        [SkipCustomFilterAttribute]
        private void GetNextCategory(List<MaterialCategory> result, Cascader parentCascader)
        {
            var nextCategory = result.Where(p => p.parent_id == parentCascader.Value).OrderBy(p => p.sort);
            foreach (var item in nextCategory)
            {
                Cascader cascader = new Cascader();
                cascader.Value = item.category_id;
                cascader.Label = item.name;
                cascader.Children = new List<Cascader>();
                parentCascader.Children.Add(cascader);

                GetNextCategory(result, cascader);
            }
        }
        /// <summary>
        /// 商品类型添加
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public async Task<ResponseModelDto> InsertMaterialCategory(MaterialCategory info)
        {
            ResponseModelDto response = new ResponseModelDto();
            var listOne = await _materialCategoryRepository.GetAllAsync(p => p.name == info.name && !p.delete_flag);
            if (listOne.Count > 0)
            {
                response.Code = -1;
                response.Message = "该类型名称已存在";
                return response;
            }
            MaterialCategory materialCategory = new MaterialCategory();
            materialCategory.name = info.name;
            materialCategory.serial_no = info.serial_no;
            materialCategory.parent_id = info.parent_id;
            materialCategory.sort = info.sort;
            materialCategory.remark = info.remark;
            materialCategory.create_time = DateTime.Now;
            materialCategory.tenant_id = info.tenant_id;
            materialCategory.delete_flag = false;
            response.Code = await _materialCategoryRepository.InsertAsync(materialCategory);
            response.Message = "添加成功";
            return response;
        }
        /// <summary>
        /// 获取单条类别
        /// </summary>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        [SkipCustomFilterAttribute]
        public async Task<MaterialCategory> GetMaterialCategoryOne(int categoryId)
        {
            var list = await _materialCategoryRepository.GetAsync(categoryId);
            return list;
        }
        /// <summary>
        /// 商品类型修改
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseModelDto> UpdateMaterialCategoryOne(MaterialCategory info)
        {
            ResponseModelDto response = new ResponseModelDto();
            var listOne = await _materialCategoryRepository.GetAllAsync(p => p.name == info.name && p.category_id != info.category_id && !p.delete_flag);
            if (listOne.Count > 0)
            {
                response.Code = -1;
                response.Message = "该类型名称已存在";
                return response;
            }
            var materialCategory = await _materialCategoryRepository.GetAsync(info.category_id);
            materialCategory.name = info.name;
            materialCategory.serial_no = info.serial_no;
            materialCategory.parent_id = info.parent_id;
            materialCategory.sort = info.sort;
            materialCategory.remark = info.remark;
            materialCategory.tenant_id = info.tenant_id;
            response.Code = await _materialCategoryRepository.UpdateAsync(materialCategory);
            response.Message = "修改成功";
            return response;
        }
        /// <summary>
        /// 商品类型批量删除
        /// </summary>
        /// <param name="isd"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<ResponseModelDto> DeleteMaterialCategoryRange(List<int> isd)
        {
            ResponseModelDto response = new ResponseModelDto();

            var listOne = _materialCategoryRepository.GetQueryable(true).Where(p => isd.Contains(p.parent_id)).ToList();
            if (listOne.Count > 0)
            {
                response.Code = -1;
                response.Message = "该类别下有子类，无法删除";
                return response;
            }
            var listTwo = from a in await _materialCategoryRepository.GetAllAsync(p => isd.Contains(p.category_id))
                          join b in await _productInfoRepository.GetAllAsync() on a.category_id equals b.category_id
                          select b;
            if (listTwo.Count() > 0)
            {
                response.Code = -1;
                response.Message = "该类别下有产品关联,无法删除";
                return response;
            }

            var categoryList = await _materialCategoryRepository.GetAllAsyncList(p => isd.Contains(p.category_id));
            categoryList.ForEach(p =>
            {
                p.delete_flag = true;
            });
            response.Code = await _materialCategoryRepository.UpdateRangeAsync(categoryList);
            response.Message = "删除成功";
            return response;
        }
    }
}
